﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Assistant;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SurfaceAd.SDK.WP;
using Windows.Phone.Speech.Recognition;
using Windows.Storage.Pickers;
using YoucaiReader.Entities;
using YoucaiReader.Entities.Model;
using YoucaiReader.Helper;
using YoucaiReader.Resources;
using YoucaiReader.UtilHelper;

namespace YoucaiReader
{
    public partial class IndexPage : PhoneApplicationPage
    {
        //阅读器使用指南
        private YoucaiReader.UserControls.ReaderHelperControl rhc = new UserControls.ReaderHelperControl();
        private ProgressIndicatorHelper piHelper;

        #region ******************************初始化******************************
        public IndexPage()
        {
            InitializeComponent();
            //
            this.AddHeaderToPivotItem();
            //
            if ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] != Visibility.Visible)
            {
                SolidColorBrush solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
                Application.Current.Resources.Add("PhoneBackgroundBrush", solidColorBrush);
            }
            if (SettingHelper.IsSettings("BookReader_Default"))
            {
                App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            }
            else
            {
                SettingHelper.SaveInToSettings("BookReader_Default", true);
                SettingHelper.SaveInToSettings("BookReader_fontSize", 26);
                SettingHelper.SaveInToSettings("BookReader_BackgroundNum", 0);
                SettingHelper.SaveInToSettings("ReaderPage_Bright", 0.08);
                SettingHelper.SaveInToSettings("ReaderPage_NightBright", 0.5);
                SettingHelper.SaveInToSettings("BookReader_NightMode", false);
                App.ReaderPage_Night = false;
                InternalDefaultBook.AddInternalBook();//App自带书籍
            }
            //
            this.Loaded += IndexPage_Loaded;
        }

        void IndexPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.piHelper = new ProgressIndicatorHelper(this);
                //初始化语音搜索
                this.InitializeRecognizer();

                //首次需要显示阅读帮助，并且不显示开屏广告
                if (!SettingHelper.IsSettings("QQReaderHelp"))
                {
                    SettingHelper.SaveInToSettings("QQReaderHelp", true);
                    this.rhc.SetPhoneApplicationPage(this, ReaderNavigatePageContants.IndexPage.ToString());
                    this.LayoutRoot.Children.Add(this.rhc);
                }
                else if (this.pivot.SelectedIndex == 0)
                {
                    base.ApplicationBar.IsVisible = true;
                    //加载开屏广告
                    this.LoadScreenAd();
                }
                //
                if (this.pivot.SelectedIndex == 0)
                {
                    //我的书架
                    this.llsLocalBookshelf.ItemsSource = App.LocalBook.T_LocalBookListViewModel();
                }
                foreach (BookListModel bookListM in App.LocalBook.T_LocalBookListViewModel())
                {
                    if (bookListM.str_Id_M != App.ReaderFileName)
                    {
                        continue;
                    }
                    SaveReaderHistory.Delete(bookListM);
                    SaveReaderHistory.Save(bookListM);
                }
                this.SetReaderHistory();
                //
                this.LoadHomeBannerAd();
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }

        }

        /// <summary>
        /// 添加标题至PivotItem
        /// <para>因为代码中的多个PivotItem只能包含一个phone:PivotItem.Header控件</para>
        /// </summary>
        private void AddHeaderToPivotItem()
        {
            //<TextBlock Margin="-20,-15,0,0" Foreground="#c1dc23" FontSize="60" Text="详细信息"/>
            this.piHome.Header = new PivotItemHelper().CreateTextBlock("首页");
            this.piBookStore.Header = new PivotItemHelper().CreateTextBlock("书架");
            this.piSetting.Header = new PivotItemHelper().CreateTextBlock("设置");
            this.piSearch.Header = new PivotItemHelper().CreateTextBlock("搜索");
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            base.Focus();
            if (base.ApplicationBar != null)
            {
                if (this.pivot.SelectedIndex != 0)
                {
                    base.ApplicationBar.IsVisible = false;
                    return;
                }
                base.ApplicationBar.IsVisible = true;
            }
        }

        /// <summary>
        /// 移除帮助信息
        /// </summary>
        public void RemoveHelp()
        {
            if (this.LayoutRoot.Children.IndexOf(this.rhc) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.rhc);
            }
        }
        #endregion ******************************初始化******************************


        #region ******************************最近阅读******************************
        #region ********************阅读历史********************
        private void EmptyBook(Image imageCoverNull, Image imageCover, TextBlock title, TextBlock progress, TextBlock author = null)
        {
            imageCoverNull.Visibility = Visibility.Visible;
            imageCover.Visibility = System.Windows.Visibility.Collapsed;
            title.Text = "暂无记录";
            progress.Text = string.Empty;
            if (author != null)
                author.Text = string.Empty;
        }
        private void SetReaderHistory()
        {
            //历史大块标识
            if (!SettingHelper.IsSettings("ReaderHistory1"))
            {
                EmptyBook(this.lstItemReaderHistoryBig_CoverNULL, this.lstItemReaderHistoryBig_Cover, this.lstItemReaderHistoryBig_Title, this.lstItemReaderHistoryBig_Author, this.lstItemReaderHistoryBig_Progress);
                return;
            }

            BookListModel bookListSettings1 = new BookListModel();
            bookListSettings1 = SettingHelper.GetValueFromSettings("ReaderHistory1") as BookListModel;
            this.lstItemReaderHistoryBig_CoverNULL.Visibility = Visibility.Collapsed;
            this.lstItemReaderHistoryBig_Cover.Visibility = Visibility.Visible;
            this.lstItemReaderHistoryBig_Cover.Source = new BitmapImage(new Uri(bookListSettings1.str_Cover_M, (InternalDefaultBook.IsInternalBook(bookListSettings1.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstItemReaderHistoryBig_Title.Text = bookListSettings1.str_Title_M;
            this.lstItemReaderHistoryBig_Author.Text = bookListSettings1.str_Author_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings1.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressListModel valueFromSettings = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings1.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                this.lstItemReaderHistoryBig_Progress.Text = GetNowTime.SetPercentageText(valueFromSettings.double_ReaderProgress_M);
            }
            //历史小左
            if (!SettingHelper.IsSettings("ReaderHistory2"))
            {
                EmptyBook(this.lstHomeReadHistorySamllLeft_CoverNULL, this.lstHomeReadHistorySamllLeft_Cover, this.lstHomeReadHistorySamllLeft_Title, this.lstHomeReadHistorySamllLeft_Progress);
                return;
            }
            BookListModel bookListSettings2 = new BookListModel();
            this.lstHomeReadHistorySamllLeft_Cover.Visibility = Visibility.Visible;
            this.lstHomeReadHistorySamllLeft_CoverNULL.Visibility = Visibility.Collapsed;
            bookListSettings2 = SettingHelper.GetValueFromSettings("ReaderHistory2") as BookListModel;
            this.lstHomeReadHistorySamllLeft_Cover.Source = new BitmapImage(new Uri(bookListSettings2.str_Cover_M, (InternalDefaultBook.IsInternalBook(bookListSettings2.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstHomeReadHistorySamllLeft_Title.Text = bookListSettings2.str_Title_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings2.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressListModel localBookProgressListM2 = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings2.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                this.lstHomeReadHistorySamllLeft_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM2.double_ReaderProgress_M);
            }
            //历史小中
            if (!SettingHelper.IsSettings("ReaderHistory3"))
            {
                EmptyBook(this.lstHomeReadHistorySamllMiddle_CoverNULL, this.lstHomeReadHistorySamllMiddle_Cover, this.lstHomeReadHistorySamllMiddle_Title, this.lstHomeReadHistorySamllMiddle_Progress);
                return;
            }
            BookListModel bookListSettings3 = new BookListModel();
            this.lstHomeReadHistorySamllMiddle_Cover.Visibility = Visibility.Visible;
            this.lstHomeReadHistorySamllMiddle_CoverNULL.Visibility = Visibility.Collapsed;
            bookListSettings3 = SettingHelper.GetValueFromSettings("ReaderHistory3") as BookListModel;
            this.lstHomeReadHistorySamllMiddle_Cover.Source = new BitmapImage(new Uri(bookListSettings3.str_Cover_M, (InternalDefaultBook.IsInternalBook(bookListSettings3.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstHomeReadHistorySamllMiddle_Title.Text = bookListSettings3.str_Title_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings3.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressListModel localBookProgressListM3 = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings3.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                this.lstHomeReadHistorySamllMiddle_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM3.double_ReaderProgress_M);
            }
            //历史小右
            if (!SettingHelper.IsSettings("ReaderHistory4"))
            {
                EmptyBook(this.lstHomeReadHistorySamllRight_CoverNULL, this.lstHomeReadHistorySamllRight_Cover, this.lstHomeReadHistorySamllRight_Title, this.lstHomeReadHistorySamllRight_Progress);
                return;
            }
            BookListModel bookListSettings4 = new BookListModel();
            this.lstHomeReadHistorySamllRight_Cover.Visibility = Visibility.Visible;
            this.lstHomeReadHistorySamllRight_CoverNULL.Visibility = Visibility.Collapsed;
            bookListSettings4 = SettingHelper.GetValueFromSettings("ReaderHistory4") as BookListModel;
            this.lstHomeReadHistorySamllRight_Cover.Source = new BitmapImage(new Uri(bookListSettings4.str_Cover_M, (InternalDefaultBook.IsInternalBook(bookListSettings4.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
            this.lstHomeReadHistorySamllRight_Title.Text = bookListSettings4.str_Title_M;
            if (SettingHelper.IsSettings(string.Concat(bookListSettings4.str_Id_M, "CurrentReaderBook")))
            {
                LocalBookProgressListModel localBookProgressListM4 = SettingHelper.GetValueFromSettings(string.Concat(bookListSettings4.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                this.lstHomeReadHistorySamllRight_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM4.double_ReaderProgress_M);
            }
        }
        #endregion ********************阅读历史********************

        private void lstItemReaderHistoryBig_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory1");
        }

        private void lstHomeReadHistorySamllLeft_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory2");
        }

        private void lstHomeReadHistorySamllMiddle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory3");
        }

        private void lstHomeReadHistorySamllRight_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            this.HomeReadHistory_Tap("ReaderHistory4");
        }

        void HomeReadHistory_Tap(string key)
        {
            if (SettingHelper.IsSettings(key))
            {
                BookListModel bookListM = new BookListModel();
                bookListM = SettingHelper.GetValueFromSettings(key) as BookListModel;
                NavigateServiceHelper.Navigate(ReaderNavigatePageContants.BookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }
        #endregion 最近阅读


        #region ******************************今日推荐******************************
        private void lstHomeReadToday_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }
        #endregion ******************************今日推荐******************************


        #region ******************************ApplicationBar******************************
        private void ApplicationBarIconButton_Feedback_Click(object sender, EventArgs e)
        {

        }

        private void ApplicationBarIconButton_Settings_Click(object sender, EventArgs e)
        {

        }
        #endregion ******************************ApplicationBar******************************


        #region ******************************书架******************************
        private void llsLocalBookshelf_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BookListModel model = this.llsLocalBookshelf.SelectedItem as BookListModel;
            if (model != null && model.int_IsDownload_M == 2)
            {
                NavigateServiceHelper.Navigate(ReaderNavigatePageContants.BookReaderPage, string.Concat("?FileName=", model.str_Id_M));
                SaveReaderHistory.Delete(model);
                SaveReaderHistory.Save(model);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void llsLocalBookshelf_Unloaded(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = false;
        }

        private void llsLocalBookshelf_Loaded(object sender, RoutedEventArgs e)
        {
            //this.menuChanged = true;
        }

        private void llsLocalBookshelf_Remove(object sender, RoutedEventArgs e)
        {
            BookListModel dataContext = (sender as MenuItem).DataContext as BookListModel;
            this.localBookListBox_DeleteDownload(dataContext);
            this.localBookSource_Delete(dataContext);
            App.LocalBook.DeleteBookList(dataContext);
        }

        private void localBookListBox_DeleteDownload(BookListModel m)
        {
            if (App.DownloadList.IsDownloadList(m.str_Id_M))
            {
                if (m.int_IsDownload_M == 0)
                {
                    App.DownloadList.DeleteDownloadList(m.str_DownUrl_M, m.str_Id_M);
                    return;
                }
                if (m.int_IsDownload_M == 1)
                {
                    App.DownloadList.DeleteDownloadClient();
                }
            }
        }

        private void localBookSource_Delete(BookListModel blm)
        {
            if (App.QQReader_StorageFile.IsFile(blm.str_Id_M))
            {
                App.QQReader_StorageFile.DeleteFile(blm.str_Id_M);
            }
            if (App.QQReader_StorageFile.IsFile(string.Concat(blm.str_Id_M, "chapterList")))
            {
                App.QQReader_StorageFile.DeleteFile(string.Concat(blm.str_Id_M, "chapterList"));
            }
            if (SettingHelper.IsSettings(blm.str_Id_M))
            {
                SettingHelper.DeleteSettings(blm.str_Id_M);
            }
            if (SettingHelper.IsSettings(string.Concat(blm.str_Id_M, "markerList")))
            {
                SettingHelper.DeleteSettings(string.Concat(blm.str_Id_M, "markerList"));
            }
            if (SettingHelper.IsSettings(string.Concat(blm.str_Id_M, "CurrentReaderBook")))
            {
                SettingHelper.DeleteSettings(string.Concat(blm.str_Id_M, "CurrentReaderBook"));
            }
            SaveReaderHistory.Delete(blm);
            GetNowTime.DeleteIsostore(blm.str_Cover_M);
            this.SetReaderHistory();
            ShellTile shellTile = ShellTile.ActiveTiles.FirstOrDefault<ShellTile>((ShellTile x) => x.NavigationUri.ToString().Contains(blm.str_Id_M));
            if (shellTile != null)
            {
                shellTile.Delete();
            }
        }
        #endregion ******************************书架******************************


        #region ******************************搜索******************************
        #region ********************语音搜索********************
        /// <summary>
        /// 初始化SpeechRecognizerUI
        /// </summary>
        private void InitializeRecognizer()
        {
            try
            {
                //创建一个语音识别类
                this.speechRecognizerUI = new SpeechRecognizerUI();
                // 语音弹出框的标题                
                this.speechRecognizerUI.Settings.ListenText = AppResources.DetailSpeechListening;// "正在为您搜索......";
                // 语音弹出框的示例内容
                this.speechRecognizerUI.Settings.ExampleText = AppResources.SearchSpeechExample;// "例如：'查应用','SurfaceAd'";
                //
                this.speechRecognizerUI.Recognizer.Grammars.AddGrammarFromPredefinedType("Search", SpeechPredefinedGrammar.WebSearch);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                MessageToastManager.Show(AppResources.DetailSpeechStartFailure);
            }
        }

        private async void StartSearchListening()
        {
            try
            {
                // 开始启动系统的语音识别UI并且等待用户的回答
                SpeechRecognitionUIResult recognizerResult = await this.speechRecognizerUI.RecognizeWithUIAsync();
                // 确认识别是否成功和音量达到要求
                switch (recognizerResult.ResultStatus)
                {
                    case SpeechRecognitionUIStatus.Busy:
                        MessageToastManager.Show(AppResources.DetailSpeechStatusBusy); break;
                    case SpeechRecognitionUIStatus.PrivacyPolicyDeclined:
                        MessageToastManager.Show(AppResources.DetailSpeechStatusPrivacy); break;
                    case SpeechRecognitionUIStatus.Preempted:
                        MessageToastManager.Show(AppResources.DetailSpeechStatusPreempted); break;
                    case SpeechRecognitionUIStatus.Cancelled:
                        MessageToastManager.Show(AppResources.DetailSpeechStatusCancelled); break;
                    case SpeechRecognitionUIStatus.Succeeded:
                        this.txtSearch.Text = recognizerResult.RecognitionResult.Text;
                        StartSearchQueryNavigation(this.txtSearch.Text, true);
                        break;
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                MessageToastManager.Show(AppResources.DetailSpeechStartFailure);
            }
        }

        private void btnMicrophone_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            IsSpeechSearch = true;
            StartSearchListening();
        }
        #endregion ********************语音搜索********************

        //
        /// <summary>
        /// 语音识别对象
        /// </summary>
        SpeechRecognizerUI speechRecognizerUI;
        private bool IsSpeechSearch = false;
        private void txtSearch_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.txtSearch.Text.Equals(AppResources.UISearchDefaultSearchKeyword))
            {
                this.txtSearch.Text = string.Empty;
            }
        }

        private void txtSearch_LostFocus(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (!this.txtSearch.Text.Equals(AppResources.UISearchDefaultSearchKeyword) && this.txtSearch.Text.Trim().Length > 0)
                {
                    StartSearchQueryNavigation(this.txtSearch.Text.Trim(), false);
                }
                else
                {
                    this.txtbSearchTotal.Text = string.Empty;
                    this.txtSearch.Text = AppResources.UISearchDefaultSearchKeyword;
                    this.txtSearch.Foreground = new SolidColorBrush(Colors.Gray);
                }
            });
        }

        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.IsSpeechSearch)
            {
                return;
            }
        }

        private void txtSearch_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //SearchApp();//焦点从txtSearch丢失后会执行搜索方法
                this.Focus();//将焦点移走，从而隐藏当前输入的软键盘                
            }
        }

        private void btnTextGo_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SearchApp();
        }

        private void SearchApp()
        {
            //执行搜索
            this.Dispatcher.BeginInvoke(() =>
            {
                if (!this.txtSearch.Text.Equals(AppResources.UISearchDefaultSearchKeyword) && this.txtSearch.Text.Trim().Length > 0)
                {
                    StartSearchQueryNavigation(this.txtSearch.Text.Trim(), false);
                }
                else
                {
                    this.txtbSearchTotal.Text = string.Empty;
                    this.txtSearch.Text = AppResources.UISearchDefaultSearchKeyword;
                    this.txtSearch.Foreground = new SolidColorBrush(Colors.Gray);
                }
            });
        }

        private void StartSearchQueryNavigation(string searchKeyword, bool speakQuery)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (string.IsNullOrWhiteSpace(searchKeyword))
                {
                    this.txtbSearchTotal.Text = string.Empty;
                    return;
                }

                this.txtbSearchTotal.Text = AppResources.DataLoading;
                this.txtSearch.Text = searchKeyword;
                this.txtSearch.Foreground = new SolidColorBrush(Colors.Black);
                LoadDataBySearchKeyword(searchKeyword, 1);
            });
        }

        void LoadDataBySearchKeyword(string searchKeyword, int pageIndex = 1)
        {
            ProgressIndicator progressIndicator = new ProgressIndicator();
            this.piHelper.StartProgressIndicator(progressIndicator, AppResources.DataLoading);

            XboxAdFictionService.XboxAdServiceSoapClient client = null;
            try
            {
                client = new XboxAdFictionService.XboxAdServiceSoapClient();
                client.GetFictionByClientCodeAndSearchwordAsync("YouthDigest",searchKeyword, 10, 1);
                client.GetFictionByClientCodeAndSearchwordCompleted += delegate(object sender, XboxAdFictionService.GetFictionByClientCodeAndSearchwordCompletedEventArgs e)
                {
                    if (e.Error != null)
                    {
                        this.txtbSearchTotal.Text = "请求异常！";
                        LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                        return;
                    }
                    //
                    LogHelper.LogInfo(e.Result, this.GetType(), MethodBase.GetCurrentMethod());
                    JsonBase<ObservableCollection<Novel>> json = JSONHelper.Deserialize<JsonBase<ObservableCollection<Novel>>>(e.Result);
                    if (json != null && json.Code.Equals(JsonCode.Success.ToString()))
                    {
                        this.txtbSearchTotal.Text = string.Format("共有 '{0}' 本相关书籍！", json.ItemsCount.ToString());
                        //加载成功
                        this.llsSearchResult.ItemsSource = json.JsonObjects;
                    }
                    else
                    {
                        this.txtbSearchTotal.Text = "返回结果错误：" + json.Code.ToString();
                    }
                    this.piHelper.StopProgressIndicator(progressIndicator);
                };
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }
        #endregion ******************************搜索搜索******************************



        #region ******************************广告******************************
        /// <summary>
        /// 加载开屏广告
        /// </summary>
        private void LoadScreenAd()
        {
            this.adHomeScreen.OnApplicationAuthEvent += adHomeScreen_OnApplicationAuthEvent;
            this.adHomeScreen.OnAdRequest += adHomeScreen_OnAdRequest;
            this.adHomeScreen.OnAdRequestFailed += adHomeScreen_OnAdRequestFailed;
            this.adHomeScreen.OnAdRequestLoaded += adHomeScreen_OnAdRequestLoaded;
            this.adHomeScreen.OnShowAdScreen += adHomeScreen_OnShowAdScreen;
            this.adHomeScreen.OnDismissAdScreen += adHomeScreen_OnDismissAdScreen;
            this.adHomeScreen.OnCloseAd += adHomeScreen_OnCloseAd;
            //this.adHomeScreen.InitAdControl(AdModeType.Normal);
        }

        private void LoadHomeBannerAd()
        {
            this.adHome.OnApplicationAuthEvent += adHome_OnApplicationAuthEvent;
            this.adHome.OnAdRequest += adHome_OnAdRequest;
            this.adHome.OnAdRequestFailed += adHome_OnAdRequestFailed;
            this.adHome.OnAdRequestLoaded += adHome_OnAdRequestLoaded;
            this.adHome.OnShowAdScreen += adHome_OnShowAdScreen;
            this.adHome.OnDismissAdScreen += adHome_OnDismissAdScreen;
            this.adHome.OnCloseAd += adHome_OnCloseAd;
            //this.adHome.InitAdControl(AdModeType.Normal);

        }
        #region ********************ScreenAd********************
        void adHomeScreen_OnCloseAd(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnDismissAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnShowAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnApplicationAuthEvent(object sender, string message)
        {
            LogHelper.LogInfo(message.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnAdRequestLoaded(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnAdRequestFailed(object sender, SurfaceAdEventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHomeScreen_OnAdRequest(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }
        #endregion ********************ScreenAd********************

        #region ********************BannerAd********************
        void adHome_OnCloseAd(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnDismissAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnShowAdScreen(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnApplicationAuthEvent(object sender, string message)
        {
            LogHelper.LogInfo(message.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnAdRequestLoaded(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnAdRequestFailed(object sender, SurfaceAdEventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }

        void adHome_OnAdRequest(object sender, EventArgs e)
        {
            LogHelper.LogInfo(e.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
        }
        #endregion ********************BannerAd********************
        #endregion ******************************广告******************************



        private void btnFilePicker_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".txt");
            //string.IsNullOrWhiteSpace
            // Launch file open picker and caller app is suspended and may be terminated if required 
            //openPicker.PickSingleFileAndContinue(); 


        }




    }
}